/* Поиск по онлайн-школе - финальная версия для GetCourse (с SVG иконками) */
(function() {
    'use strict';
    
    let debounceTimer = null;
    
    // Конфигурация
    const CONFIG = {
        minSearchLength: 2,
        debounceDelay: 300,
        searchUrl: '/pl/search/search-lesson'
    };
    
    // SVG иконки для разных типов контента
    const SVG_ICONS = {
        course: `<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M12 2L2 7L12 12L22 7L12 2Z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M2 17L12 22L22 17" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M2 12L12 17L22 12" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>`,
        lesson: `<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M2 3H8C9.06087 3 10.0783 3.42143 10.8284 4.17157C11.5786 4.92172 12 5.93913 12 7V21C12 20.2044 11.6839 19.4413 11.1213 18.8787C10.5587 18.3161 9.79565 18 9 18H2V3Z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M22 3H16C14.9391 3 13.9217 3.42143 13.1716 4.17157C12.4214 4.92172 12 5.93913 12 7V21C12 20.2044 12.3161 19.4413 12.8787 18.8787C13.4413 18.3161 14.2044 18 15 18H22V3Z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>`,
        training: `<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M12 2L15 8.5L22 9.5L17 14L18.5 21L12 17.5L5.5 21L7 14L2 9.5L9 8.5L12 2Z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>`,
        test: `<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M22 11.08V12C21.9988 14.1564 21.3005 16.2547 20.0093 17.9818C18.7182 19.709 16.9033 20.9725 14.8354 21.5839C12.7674 22.1953 10.5573 22.1219 8.53447 21.3746C6.51168 20.6273 4.78465 19.2461 3.61096 17.4371C2.43727 15.628 1.87979 13.4881 2.02168 11.3363C2.16356 9.18455 2.99721 7.13631 4.39828 5.49706C5.79935 3.85781 7.69279 2.71537 9.79619 2.24013C11.8996 1.7649 14.1003 1.98232 16.07 2.85999" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <polyline points="22 4 12 14.01 9 11.01" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>`,
        webinar: `<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <rect x="2" y="6" width="20" height="12" rx="2" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M8 12H8.01" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M12 12H12.01" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M16 12H16.01" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M6 18L8 15" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M18 18L16 15" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>`,
        default: `<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M4 4H20C21.1 4 22 4.9 22 6V18C22 19.1 21.1 20 20 20H4C2.9 20 2 19.1 2 18V6C2 4.9 2.9 4 4 4Z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M22 6L12 13L2 6" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>`
    };
    
    // Цвета фона для разных типов
    const CATEGORY_COLORS = {
        1: '#7CB291',  // Курсы
        2: '#7CB291',  // Уроки
        3: '#7CB291',  // Тренинги
        4: '#7CB291',  // Тесты
        5: '#7CB291'   // Вебинары
    };
    
    // Получение SVG иконки по категории
    function getCategoryIcon(category) {
        switch(category) {
            case 1: return SVG_ICONS.course;
            case 2: return SVG_ICONS.lesson;
            case 3: return SVG_ICONS.training;
            case 4: return SVG_ICONS.test;
            case 5: return SVG_ICONS.webinar;
            default: return SVG_ICONS.default;
        }
    }
    
    // Получение цвета по категории
    function getCategoryColor(category) {
        return CATEGORY_COLORS[category] || '#F68B2D';
    }
    
    // Основная функция поиска
    async function performSearch() {
        const searchInput = document.querySelector('.custom-search__input');
        if (!searchInput) return;
        
        const searchValue = searchInput.value.trim();
        
        if (searchValue.length < CONFIG.minSearchLength) {
            clearResults();
            return;
        }
        
        showLoading(searchInput);
        
        try {
            const url = `${CONFIG.searchUrl}?q=${encodeURIComponent(searchValue)}&ccc=${Date.now()}`;
            console.log(`&#128269; Поиск: "${searchValue}"`);
            
            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                }
            });
            
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}`);
            }
            
            const data = await response.json();
            console.log('Получены данные:', data);
            
            hideLoading();
            
            if (data.results && data.results.length > 0) {
                displayResults(data.results, searchInput, searchValue);
            } else {
                showNoResults(searchInput, searchValue);
            }
            
        } catch (error) {
            console.error('Ошибка поиска:', error);
            hideLoading();
            showError(searchInput, 'Ошибка поиска. Попробуйте позже.');
        }
    }
    
    // Отображение результатов
    function displayResults(results, searchInput, query) {
        clearResults();
        
        const resWrap = document.createElement('div');
        resWrap.classList.add('custom-search__search-results-wrap');
        
        const resultsContainer = document.createElement('div');
        resultsContainer.classList.add('custom-search__search-results');
        resWrap.appendChild(resultsContainer);
        
        results.forEach((item) => {
            const resultItem = createResultItem(item);
            resultsContainer.appendChild(resultItem);
        });
        
        const resultsInfo = document.createElement('div');
        resultsInfo.classList.add('custom-search__results-info');
        resultsInfo.style.padding = '8px 12px';
        resultsInfo.style.backgroundColor = '#f8f9fa';
        resultsInfo.style.borderTop = '1px solid #e9ecef';
        resultsInfo.style.fontSize = '12px';
        resultsInfo.style.color = '#6c757d';
        resultsInfo.innerHTML = `Найдено ${results.length} результат${getDeclension(results.length)}`;
        resultsContainer.appendChild(resultsInfo);
        
        searchInput.parentElement.appendChild(resWrap);
        console.log(`Отображены все ${results.length} результатов`);
    }
    
    function getDeclension(count) {
        if (count % 10 === 1 && count % 100 !== 11) return '';
        if (count % 10 >= 2 && count % 10 <= 4 && (count % 100 < 10 || count % 100 >= 20)) return 'а';
        return 'ов';
    }
    
    // Создание элемента результата с SVG иконкой
    function createResultItem(item) {
        const link = document.createElement('a');
        link.classList.add('custom-search__search-item');
        
        let url = '#';
        if (item.url) {
            url = item.url;
        } else if (item.onClick && item.onClick.url) {
            url = item.onClick.url;
        } else if (item.objectId) {
            url = `/teach/control/stream/view/id/${item.objectId}`;
        }
        link.href = url;
        
        const titleContainer = document.createElement('div');
        titleContainer.classList.add('custom-search__item-title-container');
        titleContainer.style.display = 'flex';
        titleContainer.style.alignItems = 'center';
        titleContainer.style.gap = '12px';
        
        // Контейнер для SVG иконки
        const iconContainer = document.createElement('div');
        iconContainer.style.width = '40px';
        iconContainer.style.height = '40px';
        iconContainer.style.borderRadius = '12px';
        iconContainer.style.display = 'flex';
        iconContainer.style.alignItems = 'center';
        iconContainer.style.justifyContent = 'center';
        iconContainer.style.flexShrink = '0';
        iconContainer.style.backgroundColor = getCategoryColor(item.category);
        
        // Вставляем SVG иконку
        const svgIcon = getCategoryIcon(item.category);
        iconContainer.innerHTML = svgIcon;
        
        // Стилизуем SVG
        const svgElement = iconContainer.querySelector('svg');
        if (svgElement) {
            svgElement.style.width = '20px';
            svgElement.style.height = '20px';
        }
        
        titleContainer.appendChild(iconContainer);
        
        // Контейнер для текста
        const textContainer = document.createElement('div');
        textContainer.style.flex = '1';
        
        // Название
        const titleSpan = document.createElement('div');
        titleSpan.classList.add('custom-search__item-title');
        titleSpan.style.fontWeight = '500';
        titleSpan.style.color = '#333';
        titleSpan.style.fontSize = '16px';
        titleSpan.style.marginBottom = '4px';
        titleSpan.innerText = item.title || 'Без названия';
        textContainer.appendChild(titleSpan);
        
        // Тип контента
        if (item.filterType || item.type) {
            const typeSpan = document.createElement('div');
            typeSpan.classList.add('custom-search__item-type');
            typeSpan.style.fontSize = '12px';
            typeSpan.style.color = '#999';
            typeSpan.innerHTML = item.filterType || item.type;
            textContainer.appendChild(typeSpan);
        }
        
        titleContainer.appendChild(textContainer);
        link.appendChild(titleContainer);
        
        // Описание
        let description = '';
        if (item.description) {
            description = item.description;
        } else if (item.shortDescription) {
            description = item.shortDescription;
        } else if (item.text) {
            description = item.text;
        }
        
        if (description) {
            const descrDiv = document.createElement('div');
            descrDiv.classList.add('custom-search__search-item-descr');
            descrDiv.style.marginTop = '8px';
            descrDiv.style.marginLeft = '-10px';
            descrDiv.style.fontSize = '13px';
            descrDiv.style.color = '#666';
            descrDiv.style.lineHeight = '1.4';
            descrDiv.innerText = description.length > 120 ? 
                description.substring(0, 120) + '...' : 
                description;
            link.appendChild(descrDiv);
        }
        
        // Стили для ссылки
        link.style.display = 'block';
        link.style.padding = '12px';
        link.style.borderBottom = '1px solid #eee';
        link.style.textDecoration = 'none';
        link.style.transition = 'all 0.2s';
        
        link.addEventListener('mouseenter', () => {
            link.style.backgroundColor = '#f8f9fa';
            link.style.transform = 'translateX(4px)';
        });
        
        link.addEventListener('mouseleave', () => {
            link.style.backgroundColor = 'transparent';
            link.style.transform = 'translateX(0)';
        });
        
        return link;
    }
    
    function clearResults() {
        const results = document.querySelectorAll('.custom-search__search-results-wrap');
        results.forEach(item => item.remove());
    }
    
    function showLoading(searchInput) {
        hideLoading();
        const loader = document.createElement('div');
        loader.classList.add('custom-search__loader');
        loader.style.position = 'absolute';
        loader.style.top = '100%';
        loader.style.left = '0';
        loader.style.right = '0';
        loader.style.backgroundColor = 'white';
        loader.style.borderRadius = '8px';
        loader.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)';
        loader.style.zIndex = '1000';
        loader.style.marginTop = '5px';
        loader.innerHTML = `
            <div style="padding: 15px; text-align: center;">
                <span style="display: inline-block; width: 20px; height: 20px; border: 2px solid #f3f3f3; border-top: 2px solid #F68B2D; border-radius: 50%; animation: spin 1s linear infinite;"></span>
                <span style="margin-left: 10px; color: #666;">Поиск...</span>
            </div>
            <style>
                @keyframes spin {
                    0% { transform: rotate(0deg); }
                    100% { transform: rotate(360deg); }
                }
            </style>
        `;
        searchInput.parentElement.style.position = 'relative';
        searchInput.parentElement.appendChild(loader);
    }
    
    function hideLoading() {
        const loader = document.querySelector('.custom-search__loader');
        if (loader) loader.remove();
    }
    
    function showError(searchInput, message) {
        const errorDiv = document.createElement('div');
        errorDiv.classList.add('custom-search__error');
        errorDiv.style.position = 'absolute';
        errorDiv.style.top = '100%';
        errorDiv.style.left = '0';
        errorDiv.style.right = '0';
        errorDiv.style.backgroundColor = '#f8d7da';
        errorDiv.style.border = '1px solid #f5c6cb';
        errorDiv.style.padding = '10px';
        errorDiv.style.marginTop = '5px';
        errorDiv.style.borderRadius = '4px';
        errorDiv.style.color = '#721c24';
        errorDiv.style.fontSize = '13px';
        errorDiv.style.zIndex = '1000';
        errorDiv.innerHTML = `&#10060; ${message}`;
        searchInput.parentElement.style.position = 'relative';
        searchInput.parentElement.appendChild(errorDiv);
        setTimeout(() => errorDiv.remove(), 4000);
    }
    
    function showNoResults(searchInput, query) {
        const noResults = document.createElement('div');
        noResults.classList.add('custom-search__no-results');
        noResults.style.position = 'absolute';
        noResults.style.top = '100%';
        noResults.style.left = '0';
        noResults.style.right = '0';
        noResults.style.backgroundColor = 'white';
        noResults.style.borderRadius = '8px';
        noResults.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)';
        noResults.style.padding = '20px';
        noResults.style.marginTop = '5px';
        noResults.style.textAlign = 'center';
        noResults.style.color = '#6c757d';
        noResults.style.zIndex = '1000';
        noResults.innerHTML = `&#128533; По запросу "${query}" ничего не найдено`;
        searchInput.parentElement.style.position = 'relative';
        searchInput.parentElement.appendChild(noResults);
        setTimeout(() => noResults.remove(), 3000);
    }
    
    function debouncedSearch() {
        if (debounceTimer) clearTimeout(debounceTimer);
        debounceTimer = setTimeout(() => performSearch(), CONFIG.debounceDelay);
    }
    
    document.addEventListener('click', (event) => {
        if (!event.target.closest('.custom-search') && 
            !event.target.closest('.custom-search__input') && 
            !event.target.closest('.search_btn')) {
            clearResults();
        }
    });
    
    function init() {
        const searchBtn = document.querySelector('.search_btn');
        const searchInput = document.querySelector('.custom-search__input');
        
        if (searchBtn) {
            searchBtn.addEventListener('click', (e) => {
                e.preventDefault();
                performSearch();
            });
        }
        
        if (searchInput) {
            searchInput.addEventListener('input', () => {
                const value = searchInput.value.trim();
                if (value.length >= CONFIG.minSearchLength) {
                    debouncedSearch();
                } else if (value.length === 0) {
                    clearResults();
                }
            });
            
            searchInput.addEventListener('keypress', (event) => {
                if (event.key === 'Enter') {
                    event.preventDefault();
                    if (debounceTimer) clearTimeout(debounceTimer);
                    performSearch();
                }
            });
        }
        
        console.log('&#9989; Поиск инициализирован (с SVG иконками)');
    }
    
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();